package com.itheima.security;

import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @author: yongjichu
 * @date: 2020/2/7 19:39
 * @description:
 */
public class UserService implements UserDetailsService {
    private BCryptPasswordEncoder passwordEncoder;

    public BCryptPasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    public  Map<String, User> map = new HashMap<>();//模拟数据库中的用户数据

    public void initData(){
        User user1 = new User();
        user1.setUsername("timli");
        user1.setPassword(passwordEncoder.encode("1234"));

    User user2 = new User();
        user2.setUsername("shaoqiang");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    /**
     * 根据用户名加载用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
        System.out.println("username:" + username);
       User userInDb = map.get(username);//模拟根据用户名查询数据库
        if(userInDb == null){
            //根据用户名没有查询到用户
            return null;
        }

        String passwordInDb = userInDb.getPassword();//模拟数据库中的密码，后期需要查询数据库

        List<GrantedAuthority> list = new ArrayList<>();
        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        list.add(new SimpleGrantedAuthority("checkitem_add"));
        list.add(new SimpleGrantedAuthority("checkitem_main"));
        if(username.equals("timli")){
            list.add(new SimpleGrantedAuthority("checkitem_delete"));
        }
        UserDetails user=new org.springframework.security.core.userdetails.User(username,passwordInDb,list);
        return user;
}
}
